import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zhibao_flutter/api/commom/common_entity.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/config/app_config.dart';
import 'package:zhibao_flutter/util/data/q1_data.dart';
import 'package:zhibao_flutter/util/float/fram_size.dart';
import 'package:zhibao_flutter/util/func/file_util.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/http/http.dart';
import 'package:zhibao_flutter/util/my_theme.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';
import 'package:zhibao_flutter/util/ui/ui.dart';
import 'package:zhibao_flutter/widget/bt/small_button.dart';
import 'package:zhibao_flutter/widget/dialog/confirm_dialog.dart';
import 'package:get/get.dart';
import 'package:open_file/open_file.dart';
import 'package:url_launcher/url_launcher.dart';

///连接超时时间为5秒
const int connectTimeOut = 5 * 1000;

///响应超时时间为7秒
const int receiveTimeOut = 7 * 1000;

class UpdateDialog extends StatefulWidget {
  final VersionRspEntity model;
  final bool isForce;

  const UpdateDialog(
    this.model, {
    this.isForce = false,
    Key? key,
  });

  @override
  State<StatefulWidget> createState() => new UpdateDialogState();
}

class UpdateDialogState extends State<UpdateDialog> {
  int _downloadProgress = 0;
  CancelToken? token;
  UploadingFlag uploadingFlag = UploadingFlag.idle;

  String get version => widget.model.version ?? "1.1.1";

  String get updateUrl => widget.model.androidUrl ?? "";

  String get updateUrlOfIOs => widget.model.iosUrl ?? "";

  @override
  Widget build(BuildContext context) {
    var _height = (FrameSize.winWidthDynamic(context) - 30) * 380 / 300;
    return WillPopScope(
      onWillPop: () async => false,
      child: new Material(
        type: MaterialType.transparency,
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.symmetric(horizontal: 30),
              width: FrameSize.winWidthDynamic(context) - 30,
              height: _height,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/bg_version_upgrade.png'),
                ),
              ),
              padding: EdgeInsets.only(bottom: 10.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  new Container(
                    height: _height / 3.5,
                    margin:
                        EdgeInsets.only(top: FrameSize.statusBarHeight() + 15),
                    width: FrameSize.winWidthDynamic(context) - 30,
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        new Text(
                          '发现新版本',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 22,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        new Text(
                          'V${widget.model.version ?? '0.0.0'}',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new Expanded(
                    child: Stack(
                      alignment: Alignment.bottomRight,
                      children: [
                        ListView(
                          padding: EdgeInsets.symmetric(
                              horizontal: 20.0, vertical: 10),
                          children: [
                            Text(
                              () {
                                // if (Q1Data.isLogin) {
                                return widget.model.content ?? "暂无内容";
//                                 } else {
//                                   return '''1.优化体验;
// 2.bug修正;''';
//                                 }
                              }(),
                              style:
                                  TextStyle(color: Colors.black, fontSize: 17),
                            )
                          ],
                        ),
                        // InkWell(
                        //   child: UnconstrainedBox(
                        //     child: Container(
                        //       width: FrameSize.winWidthDynamic(context) - 60,
                        //       padding: EdgeInsets.symmetric(
                        //           horizontal: 15, vertical: 10),
                        //       child: Column(
                        //         mainAxisAlignment: MainAxisAlignment.end,
                        //         children: [
                        //           Text(
                        //             '如果安装过程多次出现异常',
                        //             style: TextStyle(color: Colors.blue),
                        //             textAlign: TextAlign.center,
                        //           ),
                        //           Text(
                        //             '请点击官网下载',
                        //             style: TextStyle(color: Colors.blue),
                        //             textAlign: TextAlign.center,
                        //           ),
                        //         ],
                        //       ),
                        //     ),
                        //   ),
                        //   onTap: () {
                        //     launch(AppConfig.address);
                        //   },
                        // )
                      ],
                    ),
                  ),
                  getLoadingWidget(),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      !widget.isForce
                          ? new SmallButton(
                              minWidth:
                                  (FrameSize.winWidthDynamic(context) - 110) /
                                      2,
                              padding: EdgeInsets.all(0),
                              margin: EdgeInsets.only(bottom: 30),
                              gradient: LinearGradient(
                                colors: [Color(0xffD2D2D2), Color(0xffBEBEBE)],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                              ),
                              child: new Text(
                                '下次再说',
                                style: TextStyle(color: Colors.white),
                              ),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            )
                          : SizedBox(),
                      !widget.isForce ? new Space(width: 15) : new Container(),
                      new SmallButton(
                        minWidth:
                            (FrameSize.winWidthDynamic(context) - 110) / 2,
                        padding: EdgeInsets.all(0),
                        margin: EdgeInsets.only(bottom: 30),
                        gradient: LinearGradient(
                          colors: [Color(0xffFF6C29), Color(0xffFF2F18)],
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                        child: new Text(
                          '更新',
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: () async {
                          if (uploadingFlag == UploadingFlag.uploading) return;
                          if (Platform.isAndroid) {
                            _androidUpdate();
                          } else if (Platform.isIOS) {
                            _iosUpdate();
                          }
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _androidUpdate() async {
    // int updateCount = await getStoreInt(Q1Actions.updateCount());
    // print('当前更新次数::$updateCount');
    // if (updateCount != null && updateCount >= 2) {
    //   launchURL(appUrl);
    //   storeInt(Q1Actions.updateCount(), 0);
    //   return;
    // }
    // addUpdate();
    final apkPath = await FileUtil.getInstance().getSavePath("/Download/");
    var fileName = apkPath + "${Q1DataRequest.packageName}-$version.apk";
    LogUtil.d("_androidUpdate::fileName:$fileName");
    File file = new File('$fileName');
    if (await file.exists()) {
      confirmDialog(
        context,
        text: '检测到本地有$version版本安装包存在，是否直接打开？',
        onPressed: () {
          openTheApk(fileName);
          Get.back();
        },
        cancelText: '重新下载',
        onCancel: () {
          handleApk(fileName, apkPath);
        },
        okText: '打开',
      );
      return;
    } else {
      handleApk(fileName, apkPath);
    }
  }

  void handleApk(String fileName, String apkPath) {
    uploadingFlag = UploadingFlag.uploading;
    if (mounted) setState(() {});
    try {
      Dio? _client;
      if (_client == null) {
        BaseOptions options = new BaseOptions();
        options.connectTimeout = Duration(milliseconds: connectTimeOut);
        options.receiveTimeout = Duration(milliseconds: receiveTimeOut);
        options.headers = const {'Content-Type': 'application/json'};
        options.baseUrl = Environment.current;
        _client = new Dio(options);
      }

      if (!strNoEmpty(updateUrl)) {
        uploadingFlag = UploadingFlag.uploadingFailed;
        myFailToast("下载链接为空");
        return;
      }
      LogUtil.d("updateUrl::$updateUrl");

      _client.download(
        updateUrl,
        fileName,
        cancelToken: token,
        onReceiveProgress: (int count, int total) {
          if (mounted) {
            setState(() {
              _downloadProgress = ((count / total) * 100).toInt();
              if (_downloadProgress == 100) {
                if (mounted) {
                  setState(() {
                    uploadingFlag = UploadingFlag.uploaded;
                  });
                }
                File newFile = File(fileName);
                debugPrint(
                    "读取的目录:$apkPath，fileName:$fileName，newFile-existsSync:${newFile.existsSync()}，文件长度：${newFile.lengthSync()}");
                try {
                  openTheApk(fileName);
                } catch (e) {
                  LogUtil.d("Error::${e.toString()}");
                  addUpdate();
                }
                Navigator.of(context).pop();
              }
            });
          }
        },
        options: Options(
            sendTimeout: Duration(milliseconds: 15 * 1000),
            receiveTimeout: Duration(milliseconds: 360 * 1000)),
      );
    } catch (e) {
      LogUtil.d("Error::${e.toString()}");
      if (mounted) {
        setState(() {
          uploadingFlag = UploadingFlag.uploadingFailed;
        });
      }
    }
  }

  Future openTheApk(String fileName) async {
    try {
      if (await Permission.requestInstallPackages.isGranted) {
        //open an external storage image file on android 13
        OpenResult openResult = await OpenFile.open(fileName,
            type: "application/vnd.android.package-archive");
        LogUtil.d(
            "openResult-type::${openResult.type}, openResult-message::${openResult.message}");
      } else {
        launchUrl(Uri.parse(updateUrl), mode: LaunchMode.externalApplication);
      }
    } catch (e, stackTrace) {
      LogUtil.d("openTheApk::ERROR, so open the browser.");
      debugPrintStack(stackTrace: stackTrace);
      launchUrl(Uri.parse(updateUrl), mode: LaunchMode.externalApplication);
    }
  }

  void addUpdate() async {
    // int updateCount = await getStoreInt(Q1Actions.updateCount());
    // if (updateCount == null || updateCount == 0) {
    //   storeInt(Q1Actions.updateCount(), 1);
    // } else if (updateCount >= 2) {
    launch(AppConfig.host);
    //   storeInt(Q1Actions.updateCount(), 0);
    // } else {
    //   await storeInt(Q1Actions.updateCount(), updateCount + 1);
    //   int after = await getStoreInt(Q1Actions.updateCount());
    // }
  }

  Widget getLoadingWidget() {
    if (_downloadProgress != 0 && uploadingFlag == UploadingFlag.uploading) {
      return Container(
        padding: EdgeInsets.symmetric(vertical: 5.0),
        child: LinearProgressIndicator(
          valueColor:
              AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColor),
          backgroundColor: Colors.grey[300],
          value: _downloadProgress / 100,
        ),
      );
    }
    if (uploadingFlag == UploadingFlag.uploading && _downloadProgress == 0) {
      return Container(
        alignment: Alignment.center,
        height: 40,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(MyTheme.themeColor()),
            ),
            SizedBox(
              width: 5,
            ),
            Material(
              child: Text(
                '等待',
                style: TextStyle(color: MyTheme.themeColor()),
              ),
              color: Colors.transparent,
            )
          ],
        ),
      );
    }
    if (uploadingFlag == UploadingFlag.uploadingFailed) {
      return Container(
        alignment: Alignment.center,
        height: 40,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(
              Icons.clear,
              color: Colors.redAccent,
            ),
            SizedBox(
              width: 5,
            ),
            Material(
              child: Text(
                '下载超时',
                style: TextStyle(color: MyTheme.themeColor()),
              ),
              color: Colors.transparent,
            )
          ],
        ),
      );
    }
    return Container();
  }

  void _iosUpdate() {
    /// IOS暂无自动更新，如果上架AppStore直接下面链接填写AppStore的
    launchUrl(Uri.parse(updateUrlOfIOs), mode: LaunchMode.externalApplication);
  }

  @override
  void initState() {
    super.initState();
    token = new CancelToken();
  }

  @override
  void dispose() {
    if (!(token?.isCancelled ?? true)) token?.cancel();
    super.dispose();
    debugPrint("升级销毁");
  }
}

enum UploadingFlag { uploading, idle, uploaded, uploadingFailed }
